package org.carabiner.infinitest;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeNode;

class ResultTreeModel extends DefaultTreeModel implements TestStatusListener
{
  public ResultTreeModel()
  {
    super(new DefaultMutableTreeNode("Failures", true));
  }

  public void testFailed(TestEvent e)
  {
    MutableTreeNode caseNode = findNode(getRoot(), e.getTestName());
    if (caseNode == null)    
      caseNode = addNode(e.getTestName());
    TreeNode methodNode = findNode(caseNode, e.getTestMethod());
    if (methodNode == null)
      addMethodNode(caseNode, e.getTestMethod());
  }

  public void testSucceeded(TestEvent event)
  {
    MutableTreeNode caseNode = findNode(getRoot(), event.getTestName());    
    if (caseNode != null)
    {
      if (caseNode.getChildCount() == 0)
        removeNodeFromParent(caseNode);
      else
      {
        MutableTreeNode methodNode = findNode(caseNode, event.getTestMethod());
        if (methodNode != null)
          removeNodeFromParent(methodNode);
      }
    }    
  }

  private MutableTreeNode addNode(String testName)
  {  
    MutableTreeNode caseNode = new DefaultMutableTreeNode(testName, true);
    insertNodeInto(caseNode, getRootNode(), 0);
    return caseNode;
  }

  private void addMethodNode(MutableTreeNode caseNode, String testMethod)
  {
    MutableTreeNode methodNode = new DefaultMutableTreeNode(testMethod, false);
    insertNodeInto(methodNode, caseNode, 0);    
  }

  
  private MutableTreeNode getRootNode()
  {
    return (MutableTreeNode)getRoot();
  }

  private MutableTreeNode findNode(Object parentNode, String testName)
  {
    for(int i = 0; i < getChildCount(parentNode); i++)
    {
      MutableTreeNode node = (MutableTreeNode) getChild(parentNode, i);
      if (testName.equals(node.toString()))
        return node;
    }
    return null;
  }

  public int getTestCaseCount()
  {
    return getChildCount(getRoot());
  }

  public TreeNode getTestCase(int i)
  {
    return (TreeNode) getChild(getRoot(), i);
  }
}
